<template>
  <div class="alloc-menu">
    <el-card>
      <el-tree :data="menus" :props="defaultProps"
      @node-click="handleNodeClick"
      :default-checked-keys="checkedKeys"
      show-checkbox
      ref="menu-tree"
      node-key="id"
      default-expand-all></el-tree>
      <div style="margin: 20px">
        <el-button @click="onSet">清空</el-button>
        <el-button @click="onSave">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getMenuNodeList, allocateRoleMenus, getRoleMenus } from '@/services/menu'
export default {
  name: 'alloc-menu',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      menus: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      checkedKeys: []
    }
  },
  created () {
    this.loadMenu()
    this.loadRoleMenus()
  },
  methods: {
    onSet () {
      this.$refs['menu-tree'].setCheckedKeys([])
    },
    // 数据删选
    getCheckedKeys (menus) {
      console.log(menus, '========')
      // 遍历数据（将所有存在子节点的node排除，对子节点列表进行筛选）
      menus.forEach(menu => {
        if (!menu.selected) {
          return
        }
        // 检测是否有子节点
        if (menu.subMenuList) {
          return this.getCheckedKeys(menu.subMenuList)
        }
        // 说明是叶子节点，
        this.checkedKeys = [...this.checkedKeys, menu.id]
      });
    },
    async loadRoleMenus () {
      const { data } = await getRoleMenus(this.roleId)
      console.log(data)
      if (data.code === '000000') {
        this.getCheckedKeys(data.data)
      }
    },
    async onSave () {
      const keys = this.$refs['menu-tree'].getCheckedKeys()
      const { data } = await allocateRoleMenus({
        roleId: this.roleId,
        menuIdList: keys
      })
      if (data.code === '000000') {
        this.$message.success('保存成功')
        this.$router.push({
          name: 'role'
        })
      }
    },
    handleNodeClick () {
    },
    async loadMenu () {
      const { data } = await getMenuNodeList()
      console.log(data)
      if (data.code === '000000') {
        this.menus = data.data
      }
    }
  }
}
</script>

<style>

</style>
